class ImageViewer(widgets.Widget):
def __init__(
self,
image: gui.QPixmap | os.PathLike[str] | str | None = None,
*,
show_border: bool = True,
show_size: bool = False,
border_width: int = 1,
**kwargs,
):
super().__init__(**kwargs)
self._border_width = border_width
self._pixmap = gui.Pixmap()
self.set_image(image)
self.setMinimumSize(core.Size(150, 200))
self.draw_border = show_border
self.show_size = show_size
def set_image(self, pixmap: gui.QPixmap | os.PathLike[str] | str | None):
match pixmap:
case gui.QPixmap():
self._pixmap = pixmap
case os.PathLike() | str():
self._pixmap = gui.Pixmap.from_file(pixmap)
case None:
self._pixmap = gui.Pixmap()
self.updateGeometry()
self.update()
def toggle_show_size(self):
self.show_size ^= True
self.update()
def pixmap(self):
return self._pixmap
def sizeHint(self) -> core.QSize:
return self.minimumSize() if self._pixmap.isNull() else self._pixmap.size()
def paintEvent(self, event):
super().paintEvent(event)
pmap = self._pixmap
w, h = pmap.width(), pmap.height()
ow, oh = w, h
cw, ch = self.rect().width(), self.rect().height()
scaled, nw, nh = fit_image(w, h, cw, ch)
if scaled:
pmap = pmap.scaled(
int(nw * pmap.devicePixelRatio()),
int(nh * pmap.devicePixelRatio()),
constants.AspectRatioMode.IgnoreAspectRatio,
constants.TransformationMode.SmoothTransformation,
)
w = pmap.width() // pmap.devicePixelRatio()
h = pmap.height() // pmap.devicePixelRatio()
x = abs(cw - w) // 2
y = abs(ch - h) // 2
target = core.Rect(int(x), int(y), int(w), int(h))
with gui.Painter(self) as p:
p.setRenderHints(
gui.Painter.RenderHint.Antialiasing
| gui.Painter.RenderHint.SmoothPixmapTransform
)
p.drawPixmap(target, pmap)
if self.draw_border:
pen = gui.Pen()
pen.setWidth(self._border_width)
p.setPen(pen)
p.drawRect(target)
if self.show_size:
draw_size(p, target, ow, oh)